//
//  NoticeViewController.m
//  HaierGMS_APP
//
//  Created by 堂堂 on 16/9/14.
//  Copyright © 2016年 堂堂. All rights reserved.
//

#import "NoticeViewController.h"
#import "NoticeTableViewCell.h"
#import "MJRefreshNormalHeader.h"
#import "MJRefreshBackNormalFooter.h"
#import "UIColor+Hex.h"
#import "AFHTTPRequestOperationManager.h"
#import "MBProgressHUD+MJ.h"
#import "HttpReauestParam.h"
#import "UserDefaultUtil.h"
#import "NoticeDetailViewController.h"

#define ScreenHeight [[UIScreen mainScreen] bounds].size.height//获取屏幕高度，兼容性测试
#define ScreenWidth [[UIScreen mainScreen] bounds].size.width//获取屏幕宽度，兼容性测试
@interface NoticeViewController ()
@property NSMutableArray *noticeData;
@property NSArray *dataArray;
@property NSString *myear;
@property NSString *monthDay;

@property int size;
@property int page;
@property NSString *startDate;
@property NSString *endDate;


@end

@implementation NoticeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _size = 20;
    _page = 1;
    //tabView初始化
    self.table_view.delegate = self;
    self.table_view.dataSource = self;
    
    UINib *nib = [UINib nibWithNibName:@"NoticeTableViewCell" bundle:nil];
    [self.table_view registerNib:nib forCellReuseIdentifier:@"notice_cell"];
    
    
    if ([self.table_view respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.table_view setSeparatorInset:UIEdgeInsetsZero];
    }
    self.table_view.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    __unsafe_unretained UITableView *tableView = self.table_view;
    
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"刷新数据");
        
        _page = 1;
        [self getData];
        [tableView.mj_header endRefreshing];
        
    }];
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    tableView.mj_header.automaticallyChangeAlpha = YES;
    tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        [self getData];
        [tableView.mj_footer endRefreshing];
        
    }];
    [tableView.mj_header beginRefreshing];
    //初始化时间选择框
    [self initPickView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
 
    NoticeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"notice_cell"];
    
    NSDictionary *dic = self.noticeData[indexPath.row];
    
    cell.lab_title.text = dic[@"title"];
    cell.lab_content.text = dic[@"content"];
    cell.lab_date.text = dic[@"time"];
    
    if ([dic[@"isRead"] integerValue] == 0) {
        cell.left_view.backgroundColor = [UIColor colorWithHexString:@"ff7e00"];
    }else{
        cell.left_view.backgroundColor = [UIColor clearColor];
    }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    

    return _noticeData.count;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)initPickView{
    //初始化数据
    [self initData];
    
    UIView *dialogView = [[UIView alloc]initWithFrame: CGRectMake(0, ScreenHeight, ScreenWidth, 260)];
    dialogView.backgroundColor = [UIColor colorWithHexString:@"f2f2f2"];
    dialogView.tag = 111;
    dialogView.hidden = YES;
    
    UIButton * cancle = [[UIButton alloc]initWithFrame:CGRectMake(10, 10, 60, 30)];
    [cancle setTitle:@"取消" forState:UIControlStateNormal];
    cancle.titleLabel.font = [UIFont systemFontOfSize:13 ];
    [cancle setTitleColor:[UIColor colorWithHexString:@"#ff7e00"] forState:UIControlStateNormal];
    [cancle setTitleColor:[UIColor colorWithHexString:@"#55ff7e00"] forState:UIControlStateSelected];
    [cancle addTarget:self action:@selector(dialogBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton * ok = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth - 70, 10, 60, 30)];
    ok.tag = 55;
    ok.titleLabel.font = [UIFont systemFontOfSize:13 ];
    [ok setTitle:@"确定" forState:UIControlStateNormal];
    [ok setTitleColor:[UIColor colorWithHexString:@"#ff7e00"] forState:UIControlStateNormal];
    [ok setTitleColor:[UIColor colorWithHexString:@"#55ff7e00"] forState:UIControlStateSelected];
    [ok addTarget:self action:@selector(dialogBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    UIPickerView *pickView1 = [[UIPickerView alloc]initWithFrame:CGRectMake(10, 40,(ScreenWidth - 20) , 200)];
    //pickView1.backgroundColor = [UIColor greenColor];
    
    
    
    
    
    pickView1.showsSelectionIndicator = YES;
    
    
    
    [dialogView addSubview:cancle];
    [dialogView addSubview:ok];
    [dialogView addSubview:pickView1];
    
    [self.view addSubview:dialogView];
    
    pickView1.dataSource = self;
    pickView1.delegate = self;
    
    
    NSDate * date = [NSDate date];
    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit | NSCalendarUnitMonth | NSCalendarUnitDay;
    
    comps = [calendar components:unitFlags fromDate:date];
    
    int year = [comps year];
    int month = [comps month];

    if (month >= 10) {
        _startDate = [NSString stringWithFormat:@"%i-%i-01 00:00:00",year,month];
    }else{
        _startDate = [NSString stringWithFormat:@"%i-0%i-01 00:00:00",year,month];
    }
    
    if (month + 1 >= 10) {
        _endDate = [NSString stringWithFormat:@"%i-%i-01 00:00:00",year,month + 1];
    }else{
        _endDate = [NSString stringWithFormat:@"%i-0%i-01 00:00:00",year,month + 1];
    }
    
    
    [pickView1 selectRow:0 inComponent:0 animated:NO];
    [pickView1 selectRow:month - 1 inComponent:1 animated:NO];
    [self pickerView:pickView1 didSelectRow:0 inComponent:0];
    [self pickerView:pickView1 didSelectRow:month - 1 inComponent:1];
    
}

-(void)dialogBtn:(UIButton *) button{
    [self showTimeView:button];
    if (button.tag == 55) {
        //  self.oppointBtn.titleLabel.text = [NSString stringWithFormat:@"%@年%@%@",self.myear,self.monthDay,self.mTime];
        
        if (_monthDay >= 10) {
            _startDate = [NSString stringWithFormat:@"%@-%@-01 00:00:00",_myear,_monthDay];
        }else{
            _startDate = [NSString stringWithFormat:@"%@-0%@-01 00:00:00",_myear,_monthDay];
        }
        
        
        
        if ([_monthDay integerValue]+ 1 == 13) {
            _endDate = [NSString stringWithFormat:@"%i-%@-01 00:00:00",[_myear integerValue] + 1,@"01"];
        }else{
            if ([_monthDay integerValue] + 1 >= 10) {
                _endDate = [NSString stringWithFormat:@"%@-%i-01 00:00:00",_myear,[_monthDay integerValue]+ 1];
            }else{
                _endDate = [NSString stringWithFormat:@"%@-0%i-01 00:00:00",_myear,[_monthDay integerValue]+ 1];
            }
            
            
        }
        
        _page = 1;
        [self getData];
    }
}

-(NSInteger)initData{
    
    NSInteger result = 0;
    NSDate * date = [NSDate date];
    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit | NSCalendarUnitMonth | NSCalendarUnitDay;
    
    comps = [calendar components:unitFlags fromDate:date];
    
    int year = [comps year];
    
    int month = [comps month];
    
 
    
    
    NSArray * array1 = @[[NSString stringWithFormat:@"%i",year],[NSString stringWithFormat:@"%i",year + 1]];
    
    NSMutableArray *monthDay = [[NSMutableArray alloc]init];
    for (int i = 1; i <= 12; i++) {
        
        [monthDay addObject:[NSString stringWithFormat:@"%i",i]];
    }
    
    
    self.dataArray = @[array1,monthDay];
    
    return result;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    NSDictionary *dic = _noticeData[indexPath.row];
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
    NoticeDetailViewController *vc = [sb instantiateViewControllerWithIdentifier:@"notice_detail_view"];
    vc.noticeId = dic[@"id"];
    
    [self.navigationController pushViewController:vc animated:YES];
    
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    
    NSLog(@"numberOfComponentsInPickerView");
    return self.dataArray.count;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    NSLog(@"numberOfRowsInComponent");
    NSArray * array = [self.dataArray objectAtIndex:component];
    
    return array.count;
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    NSArray * array = [self.dataArray objectAtIndex:component];
    
    NSString *s = [array objectAtIndex:row];
    
    return s;
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    NSLog(@"%@",self.dataArray[component][row]);
    
    if (component == 0) {
        self.myear = self.dataArray[component][row];
    }
    if (component == 1) {
        self.monthDay = self.dataArray[component][row];
    }
}



- (IBAction)showTimeView:(id)sender {
    UIView *timeView = [self.view viewWithTag:111];
    if (timeView.hidden) {
        timeView.hidden = NO;
        
        [UIView animateWithDuration:0.5 animations:^{
            
            // 设置view弹出来的位置
            
            timeView.frame = CGRectMake(0, ScreenHeight - 260, ScreenWidth, 260);
        }];
        
    }else{
        
        [UIView animateWithDuration:0.5 animations:^{
            
            // 设置view弹出来的位置
            
            timeView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, 260);
            timeView.hidden = YES;
        }];
        
        
    }
}

- (IBAction)back_click:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

-(void) getData{
    
    NSString *userId =[UserDefaultUtil getUserId];
    NSDictionary * dic = @{@"identifier": userId ,@"page":[NSString stringWithFormat:@"%i",_page],@"size":[NSString stringWithFormat:@"%i",_size],@"startDate":_startDate,@"endDate":_endDate};
    
    NSLog(@"%@",dic);
    
    HttpReauestParam * param = [[HttpReauestParam alloc]initWithData:@"app_AppMessage_List_Get" content:[self dictionaryToJson:dic] urlType:0];
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    // [MBProgressHUD showMessage:@"获取订单"];
    [manage POST:param.SEVICE_URL parameters:param.param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:0 error:nil];
        
        
        if ([data[@"success"] boolValue]) {
            _page++;
            NSArray *orderd = data[@"result"];
            
            NSLog(@"%@",orderd);
     
            
            if (_page == 2) {
                self.noticeData = [[NSMutableArray alloc]init];
                [self.noticeData addObjectsFromArray:orderd];
            }else{
                [self.noticeData addObjectsFromArray:orderd];
            }
            
            
            [self.table_view reloadData];
            
        }else{
            [MBProgressHUD showError:data[@"errorMsg"]];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"网络连接失败"];
    }];
}


-(NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}
@end
